// webSocketService.js
import {
	mapMutations
} from 'vuex';

export default class WebSocketService {
	constructor() {
		this.socket = null;
		this.lockReconnect = false;
		this.heartbeatTime = 60 * 1000; // 心跳间隔时间，单位毫秒
	}

	initWebsocket(store, Constant) {
		return new Promise((resolve, reject) => {
			if (Constant.softType == 0) {
				this.socket = uni.connectSocket({
					url: "ws://" + Constant.socketUrl + "/websocket/" + uni.getStorageSync(
						"curUser").userName,
					success(res) {
						console.log('WebSocket连接成功', res);
					},
				});
				this.socket.onOpen((res) => {
					console.log("websocket连接成功");
					Vue.prototype.$socket = this.socket;
					resolve();
					this.headbeat(store, Constant);
				});
				this.socket.onError((res) => {
					console.log("websocket连接出现异常");
					this.reconnect(store, Constant);
				});
				this.socket.onClose((res) => {
					console.log("websocket连接关闭");
					this.reconnect(store, Constant);
				});
			} else if (Constant.softType == 1) {
				this.socket = new WebSocket("ws://" + Constant.socketUrl + "/websocket/" + uni
					.getStorageSync("curUser").userName);

				this.socket.onopen = () => {
					console.log("websocket连接成功");
					store.commit("SET_WS", this.socket);
					resolve();
					this.headbeat(store, Constant);
				};
				this.socket.onmessage = (msg) => {
					console.log("接收到socket服务器的数据====" + JSON.stringify(msg));
				};
				this.socket.onerror = () => {
					console.log("websocket连接出现异常");
					this.reconnect(store, Constant);
				};
				this.socket.onclose = () => {
					console.log("websocket连接关闭");
					this.reconnect(store, Constant);
				};
			}
		})
	}

	reconnect(store, Constant) {
		if (this.lockReconnect) return;
		this.lockReconnect = true;
		setTimeout(() => {
			this.initWebsocket(store, Constant);
		}, 1000);
		this.lockReconnect = false;
	}

	headbeat(store, Constant) {
		setTimeout(() => {
			if (this.socket.readyState === 1) {
				if (Constant.softType == 0) {
					this.socket.send({
						data: JSON.stringify({
							status: "ping"
						})
					});
				} else if (Constant.softType == 1) {
					this.socket.send(JSON.stringify({
						status: "ping"
					}));
				}
				this.headbeat(store, Constant);
			} else {
				this.reconnect(store, Constant);
			}
		}, this.heartbeatTime);
	}
}